package com.zxl.yjb.app.update;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;


import com.zxl.yjb.R;
import com.zxl.yjb.http.manager.DataManager;
import com.zxl.yjb.http.observer.ObserverOnNextListener;
import com.zxl.yjb.http.observer.ProgressObserver;
import com.zxl.yjb.utils.DisplayUtil;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;

import io.reactivex.annotations.NonNull;

@SuppressLint("ShowToast")
public class UpdateManager
{
	private static UpdateManager updateManager;
	private Context mContext;

	private static final int DOWN_NOSDCARD = 0;
	private static final int DOWN_UPDATE = 1;
	private static final int DOWN_OVER = 2;
	private static final int DOWN_FAIL = 3;
	private static final int DIALOG_TYPE_LATEST = 0;
	private static final int DIALOG_TYPE_FAIL = 1;

	private ProgressBar mProgress;
	private TextView mProgressText;
	// private ProgressDialog mProDialog;
	private int progress;
	private boolean interceptFlag;
	private String apkUrl = "";
	private String savePath = "";
	private String apkFilePath = "";
	private String tmpFilePath = "";
	private String apkFileSize;
	private String tmpFileSize;
	private String curVersionName = "";
	private CheckVersion mUpdate = new CheckVersion();
	private String checkIdentify;
	private boolean isShowMsg;
	private View progressView;
	private TextView tv_progress;
	private TextView tv_des;
	private TextView tv_ok;
	private ProgressBar pb_progress;

	private Handler mHandler = new Handler()
	{
		public void handleMessage(Message msg)
		{
			switch (msg.what)
			{
			case DOWN_UPDATE:
				mProgress.setProgress(progress);
				mProgressText.setText(tmpFileSize + "/" + apkFileSize);
				break;
				
			case DOWN_OVER:
				// downloadDialog.dismiss();
				installApk();
				break;
				
			case DOWN_NOSDCARD:
				// downloadDialog.dismiss();
				Toast.makeText(mContext, "无法下载安装文件，请检查SD卡是否挂载", Toast.LENGTH_SHORT).show();
				break;
				
			case DOWN_FAIL:
//				Toast.makeText(mContext, "检查失败", 1000).show();
				break;
			}
		};
	};

	
	
	public static UpdateManager getUpdateManager()
	{
		if (updateManager == null)
		{
			updateManager = new UpdateManager();
		}
		updateManager.interceptFlag = false;
		return updateManager;
	}

	
	
	/**
	 * 检查App更新
	 * 
	 * @param context
	 * @param isShowMsg
	 *            是否显示提示消息
	 */
	public void checkAppUpdate(Context context, final boolean isShowMsg, int checkFrom)
	{
		this.mContext = context;
		this.isShowMsg = isShowMsg;

		final int checkfrom = checkFrom;
		
		getCurrentVersion();

		// 访问接口，检测版本
		DataManager dataManager = new DataManager();

		ObserverOnNextListener<CheckVersionBean> listener = new ObserverOnNextListener<CheckVersionBean>() {
			@Override
			public void onNext(CheckVersionBean checkVersionBean) {
				mUpdate.setAppVer(checkVersionBean.getNew_version().getValue());
				mUpdate.setAppUrl(checkVersionBean.getDownload_url());
				mUpdate.setAppDesc(/*checkVersionBean.getRemark()*/"");
				// 显示检测结果
				if (mUpdate != null)
				{
					String[] currentVersionName = curVersionName.split("\\.");
					if (mUpdate.getAppVer() != null)
					{
						String[] serverVersionName = mUpdate.getAppVer()
								.split("\\.");
						int currentVersion = getVersion(currentVersionName);
						int serverVersion = getVersion(serverVersionName);
						if (currentVersion < serverVersion)
						{
							apkUrl = mUpdate.getAppUrl();
							if (apkUrl != null && !"".equals(apkUrl))
							{
								showNoticeDialog(checkVersionBean.getForce_update());
							}
						}
						else if (isShowMsg)
						{
							showLatestOrFailDialog(DIALOG_TYPE_LATEST);
						}
						else
						{
							if(checkfrom == 1)
							{
								Toast.makeText(mContext, "已经是最新版本", Toast.LENGTH_SHORT).show();
							}
						}
					}
				}
			}
		};
		dataManager.getNewVersion(new ProgressObserver<CheckVersionBean>(listener, context){
			@Override
			public void showDialog() {
			}

			@Override
			public void onError(@NonNull Throwable e) {
				super.onError(e);
				mHandler.sendEmptyMessage(DOWN_FAIL);
			}
		},new HashMap<String, String>());
	}


	public void updateDownloadProgress(int progress)
	{
		tv_progress.setText("下载进度："+progress+"%");
		pb_progress.setProgress(progress);
	}

	
	
	/**
	 * 得到版本值
	 * 
	 * @param versionName
	 * @return
	 */
	private static int getVersion(String[] versionName)
	{
		// hundreds decade units
		StringBuffer thousandsBuffer = new StringBuffer();
		StringBuffer hundredsBuffer = new StringBuffer();
		StringBuffer decadeBuffer = new StringBuffer();
		StringBuffer unitsBuffer = new StringBuffer();
		for (int i = 0; i < versionName.length; i++)
		{
			switch (i)
			{
			case 0:
				thousandsBuffer.append(versionName[i]);
				completZero(thousandsBuffer, "thousands");
				break;
			case 1:
				hundredsBuffer.append(versionName[i]);
				completZero(hundredsBuffer, "hundreds");
				break;
			case 2:
				decadeBuffer.append(versionName[i]);
				completZero(decadeBuffer, "decade");
				break;
			case 3:
				unitsBuffer.append(versionName[i]);
				completZero(unitsBuffer, "units");
				break;
			default:
				break;
			}
		}
		try {
			int thousandNum = Integer
					.parseInt(thousandsBuffer.toString().equals("") ? "0"
							: thousandsBuffer.toString());
			int hundredNum = Integer
					.parseInt(hundredsBuffer.toString().equals("") ? "0"
							: hundredsBuffer.toString());
			int decadeNum = Integer
					.parseInt(decadeBuffer.toString().equals("") ? "0"
							: decadeBuffer.toString());
			int unitsNum = Integer.parseInt(unitsBuffer.toString().equals("") ? "0"
					: unitsBuffer.toString());
			return thousandNum + hundredNum + decadeNum + unitsNum;
		}
		catch (Exception e)
		{
			return 0;
		}

	}

	
	/**
	 * 获取当前客户端版本号
	 */
	private void getCurrentVersion()
	{
		try
		{
			PackageInfo info = mContext.getPackageManager().getPackageInfo(
					mContext.getPackageName(), 0);
			curVersionName = info.versionName;
		} catch (NameNotFoundException e)
		{
			e.printStackTrace(System.err);
		}
	}
	
	
	
	/**
	 * 版本号每一个段的补零操作
	 * 
	 * @param buffer
	 *            每个段的数值串
	 * @param name
	 *            标识是指定的版本段
	 * @return
	 */
	public static StringBuffer completZero(StringBuffer buffer, String name)
	{
		if ("thousands".equals(name))
		{
			switch (buffer.toString().length())
			{
				case 1:
					buffer.append("000000000");
					break;
				case 2:
					buffer.append("00000000");
					break;
				case 3:
					buffer.append("0000000");
					break;
				default:
					break;
			}
		}
		else if ("hundreds".equals(name))
		{
			switch (buffer.toString().length())
			{
			case 1:
				buffer.append("00000000");
				break;
			case 2:
				buffer.append("0000000");
				break;
			case 3:
				buffer.append("000000");
				break;
			default:
				break;
			}
		} else if ("decade".equals(name))
		{
			switch (buffer.toString().length())
			{
			case 1:
				buffer.append("00000");
				break;
			case 2:
				buffer.append("0000");
				break;
			case 3:
				buffer.append("000");
				break;
			default:
				break;
			}
		} else if ("units".equals(name))
		{
			switch (buffer.toString().length())
			{
			case 1:
				buffer.append("00");
				break;
			case 2:
				buffer.append("0");
				break;
			default:
				break;
			}
		}
		return buffer;
	}

	
	
	
	
	/**
	 * 显示版本更新通知对话框
	 */
	private void showNoticeDialog(int forceUpdate)
	{
		if (forceUpdate == 0) {//不强制更新
			DisplayUtil.diaplayDialog(mContext, "有新版本可以下载", mUpdate.getAppDesc(), "取消", "立即更新", null, new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					downloadApk();
				}
			});
		} else if (forceUpdate == 1) {

			progressView = ((Activity)mContext).getLayoutInflater().inflate(R.layout.display_view_progress,null);
			tv_ok = (TextView) progressView.findViewById(R.id.tv_ok);
			tv_des = (TextView) progressView.findViewById(R.id.tv_des);
			tv_progress = (TextView) progressView.findViewById(R.id.tv_progress);
			pb_progress = (ProgressBar) progressView.findViewById(R.id.pb_progress);

			tv_des.setText(mUpdate.getAppDesc());
			tv_progress.setText("点击开始更新");
			DisplayUtil.diaplayForceDialog(mContext, "有新版本可以下载", mUpdate.getAppDesc(), progressView);

			tv_ok.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					pb_progress.setVisibility(View.VISIBLE);
					tv_progress.setText("下载进度：0%");
					downloadApk();
				}
			});
		}

	}

	
	
	/**
	 * 显示检测结果信息
	 */
	private void showLatestOrFailDialog(int dialogType)
	{
		if (dialogType == DIALOG_TYPE_LATEST)
		{
			if (dialogType == DIALOG_TYPE_LATEST)
			{
				Toast toast = Toast.makeText(mContext, "您当前已经是最新版本", Toast.LENGTH_SHORT);
				toast.setGravity(Gravity.CENTER,0,0);
				toast.show();
			} else if (dialogType == DIALOG_TYPE_FAIL)
			{
				Toast toast2 = Toast.makeText(mContext, "无法获取版本更新信息", Toast.LENGTH_SHORT);
				toast2.setGravity(Gravity.CENTER,0,0);
				toast2.show();
			}
		}
	}
	
	
	
	
	
	/**
	 * 下载服务器端的apk文件
	 * 
	 * @param url
	 */
	private void downloadApk()
	{
		Intent service = new Intent(mContext, DownloadApkFileService.class);
		service.putExtra("mUpdate", mUpdate);
		mContext.startService(service);
	}

	
	
	/**
	 * 安装apk文件
	 * 
	 * @param url
	 */
	private void installApk()
	{
		File apkfile = new File(apkFilePath);
		if (!apkfile.exists())
		{
			return;
		}
		Intent i = new Intent(Intent.ACTION_VIEW);
		i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
				"application/vnd.android.package-archive");
		mContext.startActivity(i);
	}

	
	
	
	/**
	 * 取消ListView,ScrollView滑动时顶部黄色边缘
	 * @param viewClass
	 * @param obj
	 */
	public static void setOverScrollViewMode(Class<?> viewClass, Object obj){
		try {
			Method method = viewClass.getMethod("setOverScrollMode", int.class);
			method.invoke(obj, View.OVER_SCROLL_NEVER);
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}
